package com.tangyh.basic.boot.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * pdf工具类
 */
@Slf4j
public class PdfUtil {

    /**
     * 给模版pdf充填数据（基于Field）
     *
     * @param inputPdfBtyes 模版pdf
     * @param map           要充填的数据
     * @return 充填好的pdf
     */
    public static byte[] putField(byte[] inputPdfBtyes, Map<String, String> map) {
        PdfReader pdfr = null;
        FileOutputStream out = null;
        ByteArrayOutputStream baos = null;
        PdfStamper stamper = null;
        try {
            pdfr = new PdfReader(inputPdfBtyes);
            baos = new ByteArrayOutputStream();
            try {
                stamper = new PdfStamper(pdfr, baos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            AcroFields form = stamper.getAcroFields();
            // 给表单添加中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);
            //遍历map装入数据
            for (Map.Entry<String, String> entry : map.entrySet()) {
                form.setField(entry.getKey(), entry.getValue());
            }
            // 禁用编辑
            stamper.setFormFlattening(true);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pdfr != null) {
                pdfr.close();
            }
        }
        return baos.toByteArray();
    }

    /**
     * 给paf添加文字(基于坐标)
     *
     * @param bytes pdf
     * @param text  内容
     * @param x     位置x（从左下角开始）
     * @param y     位置y（从左下角开始）
     * @return
     */
    public static byte[] addText(byte[] bytes, String text, float x, float y, float fontSize) {
        if (fontSize == 0) {
            fontSize = 11;
        }
        PdfReader pdfr = null;
        ByteArrayOutputStream baos = null;
        PdfStamper stamper = null;
        try {
            pdfr = new PdfReader(bytes);
            baos = new ByteArrayOutputStream();
            try {
                stamper = new PdfStamper(pdfr, baos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            PdfContentByte underContent = stamper.getOverContent(1);
            underContent.beginText();
            BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
            underContent.setFontAndSize(baseFont, fontSize);
            underContent.showTextAligned(PdfContentByte.ALIGN_CENTER, text, x, y, 0);
            underContent.endText();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pdfr != null) {
                pdfr.close();
            }
        }
        return baos.toByteArray();
    }

    /**
     * 合并多个pdf文件为一个pdf
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static byte[] mix(List<byte[]> bytes) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 创建一个新的PDF
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, bos);
        document.open();
        // 取出单个PDF的数据
        for (byte[] bs : bytes) {
            PdfReader reader = new PdfReader(bs);
            int pageTotal = reader.getNumberOfPages();
            log.info("pdf的页码数是 ==> {}", pageTotal);
            for (int pageNo = 1; pageNo <= pageTotal; pageNo++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, pageNo);
                copy.addPage(page);
            }
            reader.close();
        }
        document.close();
        byte[] pdfs = bos.toByteArray();
        bos.close();
        copy.close();
        return pdfs;

    }

    public static void main(String[] args) {

        try {
            FileInputStream fileInputStream = new FileInputStream(new File("/Users/yang/Downloads/定期定额纳税申报包（模版）.pdf.pdf"));
            BufferedInputStream bis = new BufferedInputStream(fileInputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = null;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((len = bis.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();

            Map<String, String> map = new HashMap<>();
            map.put("creditCode", "长大啊各位前台");
            map.put("subjectInfo", "阿是大姑热情和房东");
            byte[] bytes = putField(baos.toByteArray(), map);
            System.out.println(bytes.length);

            baos.close();
            bis.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
